package com.lvan.sms.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 获取随机数
 *
 * @author Lvan
 */
public class RandomUtil {

    private static final Random RANDOM = new Random();

    private static final DecimalFormat FOUR_DF = new DecimalFormat("0000");

    private static final DecimalFormat SIX_DF = new DecimalFormat("000000");

    /**
     * 生成四位随机数
     *
     * @return String
     */
    public static String getFourBitRandom() {
        return FOUR_DF.format(RANDOM.nextInt(10000));
    }

    /**
     * 生成六位随机数
     *
     * @return String
     */
    public static String getSixBitRandom() {
        return SIX_DF.format(RANDOM.nextInt(1000000));
    }

    /**
     * 给定数组，抽取n个数据
     *
     * @param list 数字数组
     * @param n    数据位数
     * @return ArrayList
     */
    public static ArrayList getRandom(List list, int n) {

        Random random = new Random();
        HashMap<Object, Object> hashMap = new HashMap<>(list.size());

        // 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {
            int number = random.nextInt(100) + 1;
            hashMap.put(number, i);
        }

        // 从HashMap导入数组
        Object[] robes = hashMap.values().toArray();
        ArrayList result = new ArrayList();

        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            result.add(list.get((int) robes[i]));
        }
        return result;
    }
}
